package com.ly.library.stickyadpter;

import java.util.ArrayList;
import java.util.List;

import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SectionIndexer;

import com.ly.quickdev.library.adapter.ListBaseAdapter;

public abstract class BaseStickyListAdapter<T extends BaseStickyBean> extends
		ListBaseAdapter<T> implements StickyListHeadersAdapter, SectionIndexer {
	private int[] mSectionIndices;
	private Character[] mSectionLetters;

	public BaseStickyListAdapter(Context context, List<T> list) {
		super(context, list);
		// TODO Auto-generated constructor stub
		if (!list.isEmpty()) {
			mSectionIndices = getSectionIndices();
			mSectionLetters = getSectionLetters();
		}
	}

	/**
	 * 获取应该在列表上出现首字母的位置的数组
	 * 
	 * @return
	 */
	private int[] getSectionIndices() {
		List<T> list = getList();
		ArrayList<Integer> sectionIndices = new ArrayList<Integer>();
		final T c1 = list.get(0);
		String lastFirstChar = c1.getStickyItem();
		sectionIndices.add(0);
		for (int i = 1; i < list.size(); i++) {
			T c = list.get(i);
			String ch = c.getStickyItem();

			if (ch != lastFirstChar) {
				lastFirstChar = ch;
				sectionIndices.add(i);
			}
		}
		int[] sections = new int[sectionIndices.size()];
		for (int i = 0; i < sectionIndices.size(); i++) {
			sections[i] = sectionIndices.get(i);
		}
		return sections;
	}

	@Override
	public abstract View initView(int position, View convertView,
			ViewGroup parent);

	@Override
	public abstract View getHeaderView(int position, View convertView,
			ViewGroup parent);

	/**
	 * 获取该位置上的字符
	 * 
	 * @return
	 */
	private Character[] getSectionLetters() {
		Character[] letters = new Character[mSectionIndices.length];
		for (int i = 0; i < mSectionIndices.length; i++) {
			letters[i] = Character.toUpperCase(getList()
					.get(mSectionIndices[i]).getStickyItem().charAt(0));
		}
		return letters;
	}

	@Override
	public long getHeaderId(int position) {
		// TODO Auto-generated method stub
		return getList().get(position).getStickyItem().charAt(0);
	}

	@Override
	public int getPositionForSection(int sectionIndex) {
		// TODO Auto-generated method stub
		if (sectionIndex >= mSectionIndices.length) {
			sectionIndex = mSectionIndices.length - 1;
		} else if (sectionIndex < 0) {
			sectionIndex = 0;
		}
		return mSectionIndices[sectionIndex];
	}

	@Override
	public int getSectionForPosition(int position) {
		// TODO Auto-generated method stub
		for (int i = 0; i < mSectionIndices.length; i++) {
			if (position < mSectionIndices[i]) {
				return i - 1;
			}
		}
		return mSectionIndices.length - 1;
	}

	@Override
	public Object[] getSections() {
		// TODO Auto-generated method stub
		return mSectionLetters;
	}
}
